package com.thunbu.lib_common.exception;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;

import com.thunbu.lib_common.function.Action;
import com.thunbu.lib_common.function.BiConsumer;

/**
 * Created by Chaolue.Fan on 2021/5/14
 * 描述:异常崩溃监听
 */
public class CrashHelper {
    private static final String TAG=CrashHelper.class.getSimpleName();
    private static BiConsumer<Action, Exception> onBugReportListener;


    //设置开启崩溃监听
    public static void turnOnReadErrorInfoPermissions(BiConsumer<Action, Exception> listener) {
        if (listener == null) return;
        onBugReportListener = listener;
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Looper.loop();
                    } catch (Throwable e) {
                        onBugReportListener.accept(new Action() {
                            @Override
                            public void run() {
                                if (CrashHandler.exceptionHandler != null) {
                                    CrashHandler.exceptionHandler.uncaughtException(Thread.currentThread(), e);

                                }
                            }
                        }, new Exception(e));
                    }
                }
            }
        });
        CrashHandler eh = new CrashHandler(Thread.getDefaultUncaughtExceptionHandler());
        Thread.setDefaultUncaughtExceptionHandler(eh);
    }


    public static class  CrashHandler implements Thread.UncaughtExceptionHandler{
        static Thread.UncaughtExceptionHandler exceptionHandler;
        public CrashHandler(Thread.UncaughtExceptionHandler handler) {
            exceptionHandler = handler;
        }


        @Override
        public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
            new Thread() {
                @Override
                public void run() {
                    Looper.prepare();
                    onBugReportListener.accept(new Action() {
                        @Override
                        public void run() {
                            if (exceptionHandler != null) {
                                //Log.e(TAG,"崩溃日志=============/n"+e.getMessage()+"/n崩溃日志结束=============/n\"");
                                exceptionHandler.uncaughtException(t, e);
                            }
                        }
                    }, new Exception(e));
                    Looper.loop();

                }
            }.start();
        }
    }

}
